import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { batchCheckAPI, type CheckRequest } from '@/api/agent';
import { getIssuesAPI, deleteIssuesAPI } from '@/api/issues';
import { ComplianceType, type ComplianceItem } from '@/types/work';
import { showMessage } from '@/components/common/MessageTip';
import {
  type AICorrectionIssue,
  type AICorrectorState,
  type CorrectionFilters,
  type CorrectionStats,
  CorrectionStatus,
  IssueSeverity,
  IssueType
} from '@/types/aiCorrector';
import { useComplianceStore } from '@/stores/useComplianceStore';
import { sortComplianceItems } from "@/utils/utils";

/***********************
 * 初始状态 & 常量
 **********************/
const initialStats: CorrectionStats = {
  totalItems: 0,
  totalIssues: 0,
  highPriorityIssues: 0,
  mediumPriorityIssues: 0,
  lowPriorityIssues: 0,
  qualityScore: 100,
  issuesByType: {
    [IssueType.TYPO]: 0,
    [IssueType.SEMANTIC]: 0,
    [IssueType.RISK_LEVEL]: 0,
    [IssueType.COMPLIANCE_STATUS]: 0
  }
};

const initialFilters: CorrectionFilters = {
  searchTerm: '',
  type: 'all',
  issueType: 'all',
  severity: 'all',
  progressStatus: 'all'
};


const initialState: AICorrectorState = {
  selectedItems: [],
  filteredItems: [],
  issues: [],
  stats: initialStats,
  status: CorrectionStatus.IDLE,
  progress: 0,
  filters: initialFilters,
  editingIssueId: null,
  modifiedItems: {},
  modifiedIssues: []
};

/***********************
 * 辅助方法
 **********************/
const calculateStats = (
  issues: AICorrectionIssue[],
  totalItems: number
): CorrectionStats => {
  const highPriorityIssues = issues.filter(i => i.severity === IssueSeverity.HIGH).length;
  const mediumPriorityIssues = issues.filter(i => i.severity === IssueSeverity.MEDIUM).length;
  const lowPriorityIssues = issues.filter(i => i.severity === IssueSeverity.LOW).length;

  const issuesByType = {
    [IssueType.TYPO]: issues.filter(i => i.type === IssueType.TYPO).length,
    [IssueType.SEMANTIC]: issues.filter(i => i.type === IssueType.SEMANTIC).length,
    [IssueType.RISK_LEVEL]: issues.filter(i => i.type === IssueType.RISK_LEVEL).length,
    [IssueType.COMPLIANCE_STATUS]: issues.filter(i => i.type === IssueType.COMPLIANCE_STATUS).length
  } as const;

  // 质量评分
  const severityWeight = {
    [IssueSeverity.HIGH]: 3,
    [IssueSeverity.MEDIUM]: 2,
    [IssueSeverity.LOW]: 1
  } as const;

  let weightedScore = 0;
  issues.forEach(issue => {
    weightedScore += severityWeight[issue.severity];
  });

  const maxPossibleScore = totalItems * 10;
  const deduction = Math.min(maxPossibleScore, weightedScore);
  const qualityScore = Math.max(0, 100 - (deduction / maxPossibleScore) * 100);

  return {
    totalItems,
    totalIssues: issues.length,
    highPriorityIssues,
    mediumPriorityIssues,
    lowPriorityIssues,
    qualityScore: Math.round(qualityScore),
    issuesByType
  };
};

/***********************
 * Zustand Store
 **********************/
interface AiCorrectorStore {
  state: AICorrectorState;
  // actions
  selectItem: (item: ComplianceItem) => void;
  deselectItem: (itemId: string) => void;
  selectAllItems: () => void;
  deselectAllItems: () => void;
  startCorrection: () => Promise<void>;
  resetCorrection: () => void;
  updateFilters: (filters: Partial<CorrectionFilters>) => void;
  exportReport: () => void;
  initFromServer: (businessId: string) => Promise<void>;
  startEdit: (issueId: string) => void;
  cancelEdit: () => void;
  updateComplianceItem: (issueid:string, itemId: string, updatedData: Partial<ComplianceItem>) => void;
  isItemModified: (issueid: string) => boolean;
  getModifiedItem: (issueid: string) => ComplianceItem | null;
  resetModifications: () => void;
  applyAllModifications: () => Promise<void>;
}

export const useAiCorrectorStore = create<AiCorrectorStore>()(
  persist(
    (set, get) => ({
      state: initialState,

      /******** 选择相关 ********/
      selectItem: (item) =>
        set(s => ({
          state: {
            ...s.state,
            selectedItems: [...s.state.selectedItems, item]
          }
        })),

      deselectItem: (itemId) =>
        set(s => ({
          state: {
            ...s.state,
            selectedItems: s.state.selectedItems.filter(i => i.id !== itemId)
          }
        })),

      selectAllItems: () => {
        set(s => ({
          state: {
            ...s.state,
            selectedItems: [...s.state.filteredItems]
          }
        }));
      },

      deselectAllItems: () =>
        set(s => ({
          state: { ...s.state, selectedItems: [] }
        })),

      /******** 检测流程 ********/
      resetCorrection: () => {
        if (get().state.issues.length > 0) {
          showMessage('warning', '请先处理未完成的问题');
          return;
        }
        set(s => ({
          state: {
            ...s.state,
            status: CorrectionStatus.SELECTING,
            issues: [],
            stats: initialStats,
            progress: 0,
            filters: initialFilters
          }
        }));
      },

      startCorrection: async () => {
        const { state: st } = get();
        // 从 useComplianceStore 获取当前业务ID
        const selectedBusinessId = useComplianceStore.getState().getSelectedBusinessId();
        if (st.status === CorrectionStatus.PROCESSING) {
          showMessage('warning', 'AI修正正在进行中，请稍候');
          return;
        }
        if (st.selectedItems.length === 0) {
          showMessage('warning', '请先选择要修正的合规项');
          return;
        }

        // 进入 processing 状态
        set(s => ({
          state: {
            ...s.state,
            status: CorrectionStatus.PROCESSING,
            progress: 0,
            issues: []
          }
        }));
        showMessage('info', 'AI修正已开始，请稍候...');
        
        // 模拟进度更新的定时器ID
        let progressTimerId: number | null = null;

        try {
          const batchSize = 15;
          const selectedItems = [...get().state.selectedItems];
          let allIssues: AICorrectionIssue[] = [];
          
          // 模拟进度更新函数
          const simulateProgress = (startProgress: number, targetProgress: number) => {
            // 清除之前的定时器
            if (progressTimerId !== null) {
              window.clearInterval(progressTimerId);
            }
            
            // 计算每次增加的进度量（目标进度的80%）
            const maxSimulatedProgress = startProgress + (targetProgress - startProgress) * 0.8;
            const step = (maxSimulatedProgress - startProgress) / 80; // 分80步完成
            let currentProgress = startProgress;
            
            // 设置定时器，每1000ms更新一次进度
            progressTimerId = window.setInterval(() => {
              currentProgress = Math.min(currentProgress + step, maxSimulatedProgress);
              set(s => ({
                state: {
                  ...s.state,
                  progress: Math.round(currentProgress)
                }
              }));
              
              // 如果达到最大模拟进度，停止定时器
              if (currentProgress >= maxSimulatedProgress) {
                if (progressTimerId !== null) {
                  window.clearInterval(progressTimerId);
                }
              }
            }, 1000); 
          };

          for (let i = 0; i < selectedItems.length; i += batchSize) {
            const batch = selectedItems.slice(i, i + batchSize);
            
            // 计算当前批次的起始和目标进度
            const startProgress = Math.round((i / selectedItems.length) * 100);
            const targetProgress = Math.round(((i + batch.length) / selectedItems.length) * 100);
            
            // 启动模拟进度更新
            simulateProgress(startProgress, targetProgress);

            const checkRequests: CheckRequest[] = batch.map((item: ComplianceItem) => {
              if (item.compliance_type === ComplianceType.RISK) {
                return {
                  item_id: item.id,
                  plan_id: selectedBusinessId ? selectedBusinessId : '',
                  compliance_type: item.compliance_type,
                  risk_level: item.risk_level,
                  description: item.description,
                  guide: item.guide,
                  title: item.title,
                  inspector: item.inspector
                };
              } else {
                return {
                  item_id: item.id,
                  plan_id: selectedBusinessId ? selectedBusinessId : '',
                  compliance_type: item.compliance_type,
                  compliance_status: item.compliance_status,
                  description: item.description,
                  guide: item.guide,
                  title: item.title,
                  inspector: item.inspector
                };
              }
            });

            const responses = await batchCheckAPI(checkRequests);

            const batchIssues: AICorrectionIssue[] = responses.map((response) => ({
              id: response.id,
              itemId: response.item_id,
              type: response.type,
              severity: response.severity,
              title: response.title,
              description: response.description,
              suggestion: response.suggestion,
              originalContent: response.originalContent,
              originalDescription: response.originalDescription
            }));

            allIssues = [...allIssues, ...batchIssues];

            // 清除模拟进度定时器
            if (progressTimerId !== null) {
              window.clearInterval(progressTimerId);
              progressTimerId = null;
            }

            const processedCount = Math.min(i + batch.length, selectedItems.length);
            const progress = Math.round((processedCount / selectedItems.length) * 100);

            // 更新真实进度
            set(s => ({
              state: {
                ...s.state,
                progress,
                issues: [...allIssues]
              }
            }));
          }

          const stats = calculateStats(allIssues, selectedItems.length);

          // 清除所有模拟进度定时器
          if (progressTimerId !== null) {
            window.clearInterval(progressTimerId);
            progressTimerId = null;
          }
          
          set(s => ({
            state: {
              ...s.state,
              status: CorrectionStatus.COMPLETED,
              progress: 100,
              issues: allIssues,
              stats
            }
          }));
          showMessage('success', `AI修正完成，共发现 ${stats.totalIssues} 个问题`);
        } catch (err) {
          console.error('AI检测出错', err);
          
          // 清除所有模拟进度定时器
          if (progressTimerId !== null) {
            window.clearInterval(progressTimerId);
            progressTimerId = null;
          }
          
          set(s => ({
            state: {
              ...s.state,
              status: CorrectionStatus.COMPLETED,
              progress: 100,
              issues: [],
              stats: { ...s.state.stats, totalIssues: 0, qualityScore: 0 }
            }
          }));
          showMessage('error', 'AI修正过程中出现错误，请稍后重试');
        }
      },

      /******** 筛选 ********/
      updateFilters: (filters) => {
        set(s => {
          const updatedFilters = { ...s.state.filters, ...filters };
          const allItems = sortComplianceItems(useComplianceStore.getState().items);
          let filteredItems = allItems;

          if (updatedFilters.searchTerm && updatedFilters.searchTerm != '') {
            const term = updatedFilters.searchTerm.toLowerCase();
            filteredItems = filteredItems.filter(item =>
              item.title.toLowerCase().includes(term) || item.description.toLowerCase().includes(term)
            );
          }

          if (updatedFilters.type && updatedFilters.type !== 'all') {
            filteredItems = filteredItems.filter(item => item.compliance_type === updatedFilters.type);
          }

          if (updatedFilters.progressStatus && updatedFilters.progressStatus !== 'all') {
            filteredItems = filteredItems.filter(item => item.progress_status === updatedFilters.progressStatus);
          }

          console.log("allItems", allItems)
          console.log("updatedFilters", updatedFilters)
          console.log("filteredItems", filteredItems)

          return {
            state: {
              ...s.state,
              filters: updatedFilters,
              filteredItems
            }
          };
        });
      },

      /******** 报告导出 ********/
      exportReport: () => {
        const issues = get().state.issues;
        console.log('导出报告', issues);
        alert('报告已导出');
      },

      /******** 内联编辑 ********/
      startEdit: (issueId: string) =>
        set(s => ({
          state: { ...s.state, editingIssueId: issueId }
        })),

      cancelEdit: () =>
        set(s => ({
          state: { ...s.state, editingIssueId: null }
        })),

      updateComplianceItem: (issueid: string, itemId: string, updatedData: Partial<ComplianceItem>) => {
        const complianceItems = useComplianceStore.getState().items;
        const original = complianceItems.find(item => item.id == itemId);
        console.log("original", original)
        console.log("complianceItems", complianceItems)
        console.log("itemId", itemId)
        if (!original) return;
           
        set(s => {
          const existing = s.state.modifiedItems[itemId] || {}; 
          return {
            state: {
              ...s.state,
              editingIssueId: null,
              modifiedItems: {
                ...s.state.modifiedItems,
                [itemId]: { ...existing, ...updatedData } 
              },
              modifiedIssues: (s.state.modifiedIssues || []).includes(issueid) 
                ? (s.state.modifiedIssues || []) 
                : [...(s.state.modifiedIssues || []), issueid] 
            }
          };
        });
      },

      isItemModified: (issueid: string) => {
        const modifiedIssues = get().state.modifiedIssues || []; // 安全检查
        return modifiedIssues.includes(issueid);
      },

      getModifiedItem: (issueid: string) => {
        const issue = get().state.issues.find(i => i.id === issueid);
        if (!issue) return null;
        
        const original = useComplianceStore.getState().items.find(i => i.id === issue.itemId);
        if (!original) return null;
        
        // 直接使用itemId获取修改数据
        const mods = get().state.modifiedItems[issue.itemId];
        return mods ? { ...original, ...mods } : original;
      },

      resetModifications: () =>
        set(s => ({
          state: { ...s.state, modifiedItems: {}, modifiedIssues: [] }
        })),

      applyAllModifications: async () => {
        const compStore = useComplianceStore.getState();
        const { modifiedItems, modifiedIssues = [] } = get().state; // 安全检查

        // 批量更新检查项数据到 useComplianceStore
        const updatePromises = Object.entries(modifiedItems).map(async ([itemId, updates]) => {
          // 现在不需要解构itemId，因为键就是itemId
          return compStore.updateItem(itemId, {
            ...updates,
            updated_at: new Date().toISOString()
          });
        });
  
        await Promise.all(updatePromises);

        // 删除相关的所有问题项
        try {
          await deleteIssuesAPI(modifiedIssues); // 使用modifiedIssues列表
          showMessage('success', '修改已应用，数据已同步');
        } catch (err) {
          console.error('删除问题失败', err);
          showMessage('error', '同步删除问题失败');
        }

        // 更新本地状态：移除已处理的问题和修改记录
        const remainingIssues = get().state.issues.filter(i => !modifiedIssues.includes(i.id));
        const stats = calculateStats(remainingIssues, get().state.selectedItems.length);

        set(s => ({
          state: {
            ...s.state,
            issues: remainingIssues,
            stats,
            modifiedItems: {},
            modifiedIssues: []
          }
        }));
      },

      initFromServer: async (businessId: string) => {
        try {
          if (!businessId) {
            showMessage('warning', '请先选择要检查的业务');
            return;
          }
          
          // 如果正在检测，不执行
          if (get().state.status === CorrectionStatus.PROCESSING) {
            return;
          }    
          
          // 先确保 ComplianceStore 的数据已加载
          const complianceStore = useComplianceStore.getState();
          // 如果 items 为空，先尝试加载数据
          if (complianceStore.items.length === 0) {
            await complianceStore.fetchItems(businessId);
          }
          
          // 获取最新的 items 并更新 filteredItems
          const complianceItems = useComplianceStore.getState().items;
          console.log("complianceItems", complianceItems)
          set(s => ({
            state: {
              ...s.state,
              filteredItems: sortComplianceItems(complianceItems)
            }
          }));
          
          const raw = await getIssuesAPI(businessId);
          const issues: AICorrectionIssue[] = raw.map(r => ({
            id: r.id,
            itemId: r.item_id,
            type: r.type as IssueType,
            severity: r.severity as IssueSeverity,
            title: r.title,
            description: r.description,
            suggestion: r.suggestion,
            originalContent: r.original_content,
            originalDescription: r.original_description
          }));
          set(s => ({
            state: {
              ...s.state,
              issues,
              // 如果有未完成问题，直接进入已完成视图
              status: issues.length > 0 ? CorrectionStatus.COMPLETED : s.state.status,
              stats: issues.length > 0 ? calculateStats(issues, s.state.selectedItems.length || 1) : s.state.stats
            }
          }));
        } catch (err) {
          console.error('初始化问题失败', err);
        }
      }
    }),
    {
      name: 'ai-corrector',
      version: 2, // 升级版本号
      partialize: (state) => ({ state: state.state }), // 仅持久化 state 字段
      migrate: (persistedState: any, version: number) => {
        // 数据迁移逻辑：从旧版本升级时初始化新字段
        if (version < 2) {
          if (persistedState?.state) {
            persistedState.state.modifiedIssues = persistedState.state.modifiedIssues || [];
          }
        }
        return persistedState;
      }
    }
  )
);

/***********************
 * 选择器 Hook（保持与旧 API 兼容）
 **********************/
export const useAiCorrector = () => useAiCorrectorStore();

// 同步合规项变化，保持 filteredItems 最新
useComplianceStore.subscribe((state) => {
  // state 类型来自 useComplianceStore，包含 items: ComplianceItem[]
  const items = state.items;
  console.log("useComplianceStore subscribe", items)
  
  const currentState = useAiCorrectorStore.getState().state;
  
  // 只在空闲或完成状态时清空选中项，在检测进行中时保持选中项
  const shouldClearSelection = currentState.status === CorrectionStatus.IDLE || 
                               currentState.status === CorrectionStatus.COMPLETED;
  
  useAiCorrectorStore.setState(s => ({
    state: {
      ...s.state,
      filteredItems: sortComplianceItems(items),
      selectedItems: shouldClearSelection ? [] : s.state.selectedItems,
    }
  }));
});

